<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Level 1</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
    <div id="chart"></div><div id="legend"></div>
    <button onclick="showMax()">Max</button>
    <button onclick="showMin()">Min</button>
    <a href="../index.html">Back</a>
    <script>
        var margin = { top: 100, right: 50, bottom: 80, left: 100 },
            width = 1200 - margin.left - margin.right,
            height = 800 - margin.top - margin.bottom,
            gridHeight = height / 12, // there are 12 months in a year
            gridMargin = { top: 3, right: 3, bottom: 3, left: 3 },
            legendSize = { height: 20, width: 300}
            months = ["January", "February", "March", "April", "May", 
            "June", "July", "August", "September", "October", "November", "December"];
        
        var svg = d3.select("#chart").append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
        
        // define axis
        var xScale = d3.scaleLinear();
        var yScale = d3.scalePoint();
        var colorScale = d3.scaleLinear();
        
        var color = d3.scaleSequential(d3.interpolateRdBu);

        // create tooltip
        var tooltip = d3.select("body")
            .append("div")
            .style("position", "absolute")
            .style("background-color", "snow")
            .style("padding", "2px")
            .style("z-index", "1")
            .style("visibility", "hidden")
            .text("a simple tooltip");
        
        // create title
        var title = svg.append("text")
            .attr("x", (width + margin.left + margin.right) / 2)             
            .attr("y", (margin.top / 2))
            .attr("text-anchor", "middle")  
            .style("font-size", "16px")
            .text("Average Maximum Monthly Temperature of Hong Kong");

        // create chart
        var g = svg.append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        // define gradient for legend 
        // https://beta.observablehq.com/@tmcw/d3-scalesequential-continuous-color-legend-example
        // https://www.visualcinnamon.com/2016/05/smooth-color-legend-d3-svg-gradient.html
        var defs = svg.append("defs");
        defs.append("linearGradient")
            .attr("id", "linear-gradient")
            .selectAll("stop")
            .data(color.ticks().reverse().map((t, i, n) => ({ offset: i/n.length, color: color(t) })))
            .enter().append("stop")
            .attr("offset", d => d.offset)
            .attr("stop-color", d => d.color);
        var legend = g.append('g')
            .attr("transform", "translate(0," + (height + 10 + legendSize.height) + ")")
        legend.append("rect")
            .attr("width", legendSize.width)
            .attr("height", legendSize.height)
            .style("fill", "url(#linear-gradient)");

        var grids;

        d3.csv("./data/temperature_daily.csv").then(function(data) {
            // get data from csv
            console.log(data)

            // Data preprocess
            var parseTime = d3.timeParse("%Y-%m-%d");
            var formatTime = d3.timeFormat("%Y-%m");
            data.forEach(element => {
                var date = parseTime(element.date);
                element.year = date.getFullYear();
                element.month = months[date.getMonth()];
                element.ym = formatTime(date);
            });
            var _data = d3.nest()
                .key(function(d) { return d.ym; })
                .rollup(function(d) {  
                  return  {"month": d[0].month, 
                    "year": d[0].year, 
                    "avg_min": d3.sum(d, function(d) {return d.min_temperature;}) / d.length,
                     "avg_max": d3.sum(d, function(d) {return d.max_temperature;}) / d.length}})
                .entries(data);
            console.log(_data);

            var xRange = d3.extent(data.map(e => e.year));
            var minTemp = d3.min(_data.map(e => e.value.avg_min));
            var maxTemp = d3.max(_data.map(e => e.value.avg_max));
            var gridWidth = width / (xRange[1] - xRange[0] + 1);
            xScale.domain(xRange).range([gridWidth/2, width - gridWidth/2]);
            yScale.domain(months).range([gridHeight/2, height - gridHeight/2]);
            color.domain([maxTemp, minTemp]);
            colorScale.domain(color.domain()).range([legendSize.width, 0]);

            g.append("g")
                .call(d3.axisTop(xScale).ticks(xRange[1] - xRange[0] + 1, d3.format("d")));

            g.append("g")
                .call(d3.axisLeft(yScale));

            grids = g.append("g").selectAll(".dot")
                .data(_data)
                .enter().append("rect")
                .attr("x", d => xScale(d.value.year) - gridWidth / 2 + gridMargin.left)
                .attr("y", d => yScale(d.value.month) - gridHeight / 2 + gridMargin.top)
                .attr("width", gridWidth - gridMargin.left - gridMargin.right)
                .attr("height", gridHeight - gridMargin.top - gridMargin.bottom)
                .attr("fill", d => color(d.value.avg_max))
                .on('mouseover', function(d) {
                    tooltip.style("visibility", "visible").text("Date: " + d.key + " Avg. max: " + d.value.avg_max.toFixed(1));
                })
                .on("mousemove", function(){return tooltip.style("top", (event.pageY-12)+"px").style("left",(event.pageX+12)+"px");})
                .on("mouseout", function(){return tooltip.style("visibility", "hidden");});
            
            colorAxis = legend.append('g')
                .attr("transform", "translate(0," + legendSize.height + ")")
                .call(d3.axisBottom(colorScale));
        })

        function showMax() {
            title.text("Average Maximum Monthly Temperature of Hong Kong");
            grids
                .on('mouseover', function(d) {
                    tooltip.style("visibility", "visible").text("Date: " + d.key + " Avg. max: " + d.value.avg_max.toFixed(1));
                })
                .transition().attr("fill", d => color(d.value.avg_max));
        }

        function showMin() {
            title.text("Average Minimum Monthly Temperature of Hong Kong");
            grids
                .on('mouseover', function(d) {
                    tooltip.style("visibility", "visible").text("Date: " + d.key + " Avg. min: " + d.value.avg_min.toFixed(1));
                })
                .transition().attr("fill", d => color(d.value.avg_min));
        }
    </script>
</body>
</html>